package cc.lzmsh.controller;

import cc.lzmsh.pojo.User;
import cc.lzmsh.pojo.dto.LoginDTO;
import cc.lzmsh.pojo.dto.RegisterDTO;
import cc.lzmsh.pojo.result.Result;
import cc.lzmsh.service.UserService;
import cc.lzmsh.utils.Md5Util;
import cc.lzmsh.utils.ThreadLocalUtil;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * Author:   msh
 * Date:     2024/9/25 下午2:33
 * Description:
 */

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/register")
    public Result register(@RequestBody RegisterDTO registerDTO) {
        return userService.register(registerDTO);
    }

    @PostMapping("/login")
    public Result login(@RequestBody LoginDTO loginDTO) {
        return userService.login(loginDTO);
    }

    @GetMapping("/userInfo")
    public Result userInfo(@RequestHeader(name = "token") String token) {
        return Result.success(userService.getUserInfo());
    }

    @PutMapping("/update")
    public Result updateUserInfo(@RequestBody User user) {
        return userService.updateUserInfo(user);
    }

    // 更换头像
    @PutMapping("/updateAvatar")
    public Result updateUserPic(@RequestParam("avatarUrl") @URL String avatarUrl) {
        return userService.updateUserInfo(new User(null, null, null, null, null, avatarUrl, null, null));
    }

    // 修改密码
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params, @RequestHeader("token")String token) {
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要的参数");
        }
        //原密码是否正确
        //调用userService根据用户名拿到原密码，再和old_pwd比对
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findByUserName(username);
        if (!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))) {
            return Result.error("原密码填写不正确");

        }
        //newPwd和rePwd是否一样
        if (!rePwd.equals(newPwd)) {
            return Result.error("两次填写的新密码不一样");
        }

        // 删除redis中对应的token
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        opsForValue.getOperations().delete(token);

        //2.调用service完成密码更新;
        return userService.updatePwd(newPwd);


    }
}
